<script lang="tsx">

import { PropType, defineComponent, ref, unref } from 'vue'
import { PageListSchema } from "../../../types/lowcode"
import { useParseParam, useGetFormUpdateParam ,useRemoveEmptyObject} from "../../../use/useRequest"
import { VXETable, VxeGridInstance } from 'vxe-table'
import request from '@/config/axios'
import type { FormInstance } from 'element-plus'

//model第一次会调用2次的问题，需要怎么解决
export default defineComponent({
    name: 'ZwTemplateListEditPage',
    props: {
        schema: {
            type: Object as PropType<PageListSchema>,
            default: function () {
                return {}
            }
        }
    },
    emits: ["emitEvents"],
    setup(props, { expose ,emit}) {

        const gridRef = ref<VxeGridInstance>()
        const refForm = ref<FormInstance>()
        const modelVisible = ref(false) //是否弹窗
        const modelTitle = ref("弹窗") //弹窗标题
        const modelType = ref("") //弹窗类型
        let selectRow = ref(null) //当前弹框的行

        //         // 创建一个简单输入框渲染
        // VXETable.renderer.add('checkbox', {
        //   // 可编辑激活模板
        //   renderEdit (renderOpts, params) {
        //     let { row, column } = params
        //     console.log("row",row, renderOpts)
        //     return <zw-checkbox v-model={ row[column.field] } schema={renderOpts}></zw-checkbox>
        //   },
        //   // 可编辑显示模板
        //   renderCell (renderOpts, params) {
        //     let { row, column } = params
        //     return [
        //       <span>{ row[column.field] }</span>
        //     ]
        //   },
        // })

        const keyField = props.schema.tableConfig.rowConfig.keyField

        const getQueryRequestConfig = () => {//获得查询的请求配置
            let proxyConfig = { ...props.schema.proxyConfig }
            return async ({ page, sorts, filters }) => {
                let reqBody = useParseParam(proxyConfig.query, undefined)
                
                if(page.currentPage){
                    reqBody.params["pageNo"] = page.currentPage
                    reqBody.params["pageSize"] = page.pageSize
                }

                reqBody.params = Object.assign(reqBody.params,
                 useRemoveEmptyObject(props.schema.searchConfig!.data))
                let [data, err] = await request.request(reqBody)
                if (data) {
                    if(!page.currentPage && proxyConfig.props?.list){//默认取result
                        return {
                            "list":data
                        }
                    }else{
                        return data;
                    }
                    
                } else {
                    VXETable.modal.message({ content: '列表接口请求失败！' + err.msg, status: 'error' })

                }
            }
        }

        const getDeleteRequestConfig = () => {//配置删除请求
            return async ({ body }) => {
                let ids = body.removeRecords.map(v=>{
                    return v[keyField]
                }).toString()
                let reqBody = { ...props.schema.proxyConfig.delete}
                reqBody.params[keyField] = ids
                return request.request(reqBody)
            }
        }

        const getImportConfig = () => {
            let proxyConfig = { ...props.schema.proxyConfig }
            return {
                remote: true,
                types: ['xlsx'],
                modes: ['insert'],
                // 自定义服务端导入
                async importMethod({ file }) {
                    const formBody = new FormData()
                    formBody.append('file', file)
                    let reqBody = useParseParam(proxyConfig.import, undefined)
                    reqBody.params = formBody;
                    let [data, err] = await request.request(reqBody)
                    if (data) {
                        VXETable.modal.message({ content: `成功导入 ${data.result.insertRows} 条记录！`, status: 'success' })
                        // 导入完成，刷新表格
                        gridRef.value?.commitProxy('query')
                    } else {
                        console.error(err)
                        VXETable.modal.message({ content: '导入失败，请检查数据是否正确！', status: 'error' })
                    }
                }
            }
        }

        const getExportConfig = () => {//导出配置
            let proxyConfig = { ...props.schema.proxyConfig }
            return {
                remote: true,
                types: ['xlsx'],
                modes: ['current', 'selected', 'all'],
                // 自定义服务端导出
                async exportMethod({ options }) {
                    const $grid = gridRef.value
                    const proxyInfo = $grid?.getProxyInfo()
                    // 传给服务端的参数
                    const body = {
                        filename: options.filename,
                        sheetName: options.sheetName,
                        isHeader: options.isHeader,
                        original: options.original,
                        mode: options.mode,
                        pager: proxyInfo ? proxyInfo.pager : null,
                        ids: options.mode === 'selected' ? options.data.map((item) => item.id) : [],
                        fields: options.columns.map((column) => {
                            return {
                                field: column.field,
                                title: column.title
                            }
                        })
                    }
                    // 开始服务端导出
                    // return fetch(`${serveApiUrl.value}/api/pub/export`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(response => response.json()).then(data => {
                    //     if (data.id) {
                    //         VXETable.modal.message({ content: '导出成功，开始下载', status: 'success' })
                    //         // 读取路径，请求文件
                    //         fetch(`${serveApiUrl.value}/api/pub/export/download/${data.id}`).then(response => {
                    //             response.blob().then(blob => {
                    //                 // 开始下载
                    //                 VXETable.saveFile({ filename: '导出数据', type: 'xlsx', content: blob })
                    //             })
                    //         })
                    //     }
                    // }).catch(() => {
                    //     VXETable.modal.message({ content: '导出失败！', status: 'error' })
                    // })
                }
            }
        }


        const getPageConfig = () => {//分页配置
            return {
                pageSize: 10,
                pageSizes: [10, 20, 50, 100, 200, 500]
            }
        }

        //watch()
        const getTableConfig = () => {
            let tableConfig = { ...props.schema.tableConfig }
            let ajax = tableConfig.proxyConfig.ajax;
            if(!props.schema.isInDialog){
                tableConfig['height'] = "100%"
            }
            
            if (!tableConfig.pagerConfig && !tableConfig.pagerConfig.enabled) {//分页配置
                tableConfig.pagerConfig = getPageConfig()
            }
            if (!ajax?.query && !tableConfig.proxyConfig.autoLoad) {//获取查询的接口配置
                ajax['query'] = getQueryRequestConfig();
            }

            if (!ajax.delete) {//配置删除的接口
                ajax['delete'] = getDeleteRequestConfig();
            }

            let toolbarConfig = { ...tableConfig.toolbarConfig }
            //配置导入
            if (toolbarConfig.import && !tableConfig.importConfig) {
                tableConfig['importConfig'] = getImportConfig();
            }

            //配置导出
            if (toolbarConfig.export && !tableConfig.exportConfig) {
                tableConfig['exportConfig'] = getExportConfig();
            }

            //删除自定义的配置
            const delArr: string[] = ['opts', 'buttons']
            delArr.forEach(v => {
                delete tableConfig[v]
            })
            return tableConfig;
        }

        const renderOptColumn = (row) => {//渲染操作列
            let opts = unref(props.schema.tableConfig.opts)
            if (opts) {
                return (
                    opts.map(opt => {
                        return <zw-text-button {...opt} onClick={() => opt.event(row)}></zw-text-button>
                    })
                )
            }
        }

        const renderButtons = () => {//渲染表单头的按钮
            var buttons = unref(props.schema.tableConfig.buttons)
            if (buttons) {
                return (
                    buttons.map(button => {
                        return <zw-button {...button} onClick={() => button.event()} />
                    })
                )
            }
        }



        const submitForm = () => {//提交请求
            var formSchema = unref(props.schema.createConfig)
            refForm.value?.validate(async () => {
                let proxyConfig = { ...props.schema.proxyConfig }
                let reqBody = useParseParam(proxyConfig.create, undefined)
                reqBody.params = Object.assign(reqBody.params, formSchema?.data)
                let [data, err] = await request.request(reqBody)
                if (data) {
                    gridRef.value?.commitProxy('query')
                    closeModel();
                } else {
                    console.error(err)
                    VXETable.modal.message({ content: '保存失败！', status: 'error' })

                }
            })
        }

        const updateForm = () => {//更新表单
            var formSchema = unref(props.schema.editConfig)
            refForm.value?.validate(async () => {
                let proxyConfig = { ...props.schema.proxyConfig }
                let reqBody = useParseParam(proxyConfig.update, undefined)
                useGetFormUpdateParam(reqBody, formSchema, keyField);

                let [data, err] = await request.request(reqBody)
                if (data) {
                    gridRef.value?.commitProxy('query')
                    closeModel()
                } else {
                    console.error(err)
                }
            })
        }

        const renderCreateModal = () => {//创建新增表单
            let formSchema = unref(props.schema.createConfig)
            modelTitle.value = formSchema?.title as string;
            return {
                default: function () {
                    return <zw-form schema={formSchema} ref={refForm}></zw-form>
                },
                footer: function () {
                    return <zw-button type="primary" title="保 存" onClick={submitForm}></zw-button>
                }
            }
        }

        const getDetailData = async (row) => {
            let proxyConfig = { ...props.schema.proxyConfig }
            let reqBody = useParseParam(proxyConfig.detail, undefined)
            reqBody.params[keyField] = row[keyField]
            let [data, err] = await request.request(reqBody)
            if (data) {
                return data
            } else {
                console.error("请求失败", err)
                return undefined
            }
        }

        const renderEditModal = (row) => {//创建编辑表单--渲染函数不能有异步
            let formSchema = unref(props.schema.editConfig)
            modelTitle.value = formSchema?.title as string;
            getDetailData(row).then(data => {
                formSchema!.data = data
            })
            return {
                default: function () {
                    return <zw-form schema={formSchema} ref={refForm}></zw-form>
                },
                footer: function () {
                    return <zw-button type="primary" title="更 新" onClick={updateForm}></zw-button>
                }
            }
        }

        const onJumpDetail = (row) => {//跳转到详情表单
            modelType.value = "detail";
            modelVisible.value = true;
            selectRow.value = row;
        }

        const onJumpModelEdit = (row) => {//跳转到编辑表单
            modelType.value = "edit";
            modelVisible.value = true;
            selectRow.value = row;
        }

        const onDeleteItem =  (row) => {//删除列表项
            if (row) {//删除单条信息
                VXETable.modal.confirm({ id: `cfm_${row[keyField]}`, content: "您确定要删除所选记录吗？", escClosable: true }).then(async (type) => {
                    if (type === 'confirm') {
                        let reqBody = { ...props.schema.proxyConfig.delete}
                        reqBody.params[keyField] = row[keyField]
                        let [data, ] = await request.request(reqBody)
                        if(data){
                            VXETable.modal.message({ id: `msg_${row[keyField]}`, content: "删除成功", status: 'success' })
                            gridRef.value?.commitProxy('query')
                        }else{
                            VXETable.modal.message({ id: `msg_${row[keyField]}`, content: "删除失败", status: 'warning' })
                        }
                    }
                })
            } else {//删除多条信息
                gridRef.value?.commitProxy('delete')
            }

        }

        const onJumpModelCreate = () => {//跳转到新增表单
            modelType.value = "create";
            modelVisible.value = true;
        }

        const renderDetailModal = (row) => {//创建编辑表单
            let formSchema = unref(props.schema.detailConfig)
            modelTitle.value = formSchema?.title as string;
            getDetailData(row).then(data => {
                formSchema!.data = data
            })
            return {
                default: function () {
                    return <zw-description schema={formSchema} />
                },
            }
        }

        const closeModel = () => {
            modelType.value = "";
            modelVisible.value = false;
        }

        const renderModal = () => {//渲染新增、编辑、详情页面
            if (!modelVisible.value) {
                return
            }

            if (modelType.value == "detail") {
                return renderDetailModal(selectRow.value)
            } else if (modelType.value == "edit") {
                return renderEditModal(selectRow.value);
            } else if (modelType.value == "create") {
                return renderCreateModal()
            }
        }

        const onRunGridCode = (code)=>{
            gridRef.value?.commitProxy(code)
        }

        const refGird = ()=>{
            return gridRef.value
        }

        const emitEvent = (params)=>{
            emit("emitEvents", params)
        }

        expose({
            onJumpModelEdit,
            onJumpModelCreate,
            onDeleteItem,
            refGird,
            emitEvent,
            onRunGridCode,
        })

        const onSearch = ()=>{
            gridRef.value?.commitProxy('query')
        }

        return () => (
            <content-page>
                { props.schema.searchConfig ? <zw-search schema={props.schema.searchConfig} onSearch={onSearch}></zw-search> : ""}            
                <vxe-grid ref={gridRef} {...getTableConfig()}>
                    {{
                        slotButtons: function () {
                            return renderButtons()
                        },
                    }}
                </vxe-grid>
            </content-page >
        )
    }
})
</script>

<style lang="less" scoped></style>